﻿using Blm.Utils.Extensions;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using VisionCloud.Core.Model.Ms;
using VisionCloud.Domain.Common;
using VisionCloud.Domain.DtoModel.Ms;
using VisionCloud.Domain.Repository.Interface.Ms;
using VisionCloud.Domain.UnitOfWork;
using VisionCloud.Utility;

namespace VisionCloud.Service.Ms
{
    public class MeasureTemplateService
    {
        public IUnitOfWork UnitOfWork { get; set; }

        public IMsProjectRepository MsProjectRepository { get; set; }

        public IMsHouseMapRepository MsHouseMapRepository { get; set; }

        public IMsHouseMapPointRepository MsHouseMapPointRepository { get; set; }

        public IMsMeasureTemplateRepository MsMeasureTemplateRepository { get; set; }

        /// <summary>
        /// 根据户型图Id获取测量项设计值
        /// </summary>
        /// <param name="houseMapId">户型图编号</param>
        /// <returns></returns>
        public async Task<List<MsMeasureTemplateDto>> GetMsMeasureTemplate(string houseMapId)
        {
            if (string.IsNullOrWhiteSpace(houseMapId))
                throw new OperationException("YB0110".SLocalize());
            return await MsMeasureTemplateRepository.GetMeasureTemplate(houseMapId.ToGuid());
        }

        /// <summary>
        /// 根据户型图和站点获取人工测量项
        /// </summary>
        /// <param name="houseMapId">户型图编号</param>
        /// <param name="pointId">站点编号</param>
        /// <returns></returns>
        public async Task<List<MeasureItem>> GetManualMeasureItem(Guid houseMapId, Guid pointId)
        {
            return await MsMeasureTemplateRepository.GetManualMeasureItem(houseMapId, pointId);
        }

        /// <summary>
        /// 获取测量项模板
        /// </summary>
        /// <param name="houseMapId">户型图Id</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<List<MsMeasureTemplateDto>> GetMeasureItemTemplate(Guid houseMapId)
        {
            var houseMap = MsHouseMapRepository.GetById(houseMapId);
            if (houseMap == null)
            {
                throw new OperationException(AjaxCode.Fail, "YB0129".SLocalize());
            }
            return await MsMeasureTemplateRepository.GetMeasureTemplate(houseMapId);
        }

        /// <summary>
        /// 更新户型图测量项模板
        /// </summary>
        /// <param name="models"></param>
        /// <returns></returns>
        /// <exception cref="OperationException"></exception>

        public async Task<ApiResult> UpdateHouseTypeTemplate(MSHouseTypeTemplateDTO models)
        {
            var houseMapId = models.HouseMapId;

            if (houseMapId == Guid.Empty)
            {
                throw new OperationException("YB0130".SLocalize());
            }
            var map = await MsHouseMapRepository.GetByIdAsync(houseMapId);
            if (map == null)
            {
                throw new OperationException("YB0131".SLocalize());
            }
            if (models.keyAndName != null)
            {
                foreach (var item in models.keyAndName)
                {
                    if (item.Name.IsSpecialChars())
                    {
                        // 分户类型不能含特殊字符
                        throw new OperationException("YB0462".SLocalize());
                    }
                }
            }
            map.HouseType = JsonConvert.SerializeObject(models.keyAndName);
            Dictionary<int, string> kv = models.keyAndName.ToDictionary(item => item.Key, item => item.Name);
            var mapPoint = await MsHouseMapPointRepository.GetMsHouseMapPointList(houseMapId);
            foreach (var p in mapPoint)
            {
                if (!p.HouseTypeKey.HasValue)
                    continue;
                if (kv.Keys.Contains(p.HouseTypeKey.Value))
                    p.HouseTypeName = kv[p.HouseTypeKey.Value];
                else
                {
                    p.HouseTypeKey = null;
                    p.HouseTypeName = string.Empty;
                }
            }
            MsProjectRepository.UpdateProjectVersion(map.ProjectId);
            await UnitOfWork.SaveChangesAsync();
            var result = new ApiResult();
            result.Code = AjaxCode.Success;
            return result;
        }

        /// <summary>
        /// 新增/更新测量项设计值模板
        /// </summary>
        /// <param name="models"></param>
        /// <returns></returns>
        /// <exception cref="OperationException"></exception>
        public async Task<ApiResult> UpdateMeasureTemplate(List<MsMeasureTemplateDto> models)
        {
            if (models == null || models.Count == 0)
            {
                throw new OperationException("YB0132".SLocalize());
            }

            var houseMapId = models[0].HouseMapId;

            if (houseMapId == Guid.Empty)
            {
                throw new OperationException("YB0130".SLocalize());
            }

            var templates = await MsMeasureTemplateRepository.GetMeasureTemplate(houseMapId);
            templates?.ForEach(t =>
            {
                var dbTemplate = t.CopyTo<MsMeasureTemplate>();
                MsMeasureTemplateRepository.Remove(dbTemplate, true);
            });

            List<MsMeasureTemplate> entities = new List<MsMeasureTemplate>();
            foreach (var model in models)
            {
                var entity = model.CopyTo<MsMeasureTemplate>();
                if (entity.Code == "r-kaijianjinshenpiancha")
                {
                    entity.Type = 1;
                }
                entity.HouseMapId = model.HouseMapId.ToGuid();
                entity.Id = model.Id;
                entity.Title = model.Title;
                entity.Code = model.Code;
                entity.Unit = entity.Unit ?? "mm";
                entity.Type = model.Type;
                entity.IsDeleted = false;
                entity.DesignValues = model.DesignValues.ToJsonStr();
                entity.LastUpdatedBy = OperatorProvider.Get().Id;
                entity.LastUpdatedDate = DateTime.Now;
                entity.CreatedBy = OperatorProvider.Get().Id;
                entity.CreatedDate = DateTime.Now;
                entities.Add(entity);
            }
            MsMeasureTemplateRepository.AddRange(entities);
            var map = await MsHouseMapRepository.GetByIdAsync(houseMapId);
            MsProjectRepository.UpdateProjectVersion(map.ProjectId);
            await UnitOfWork.SaveChangesAsync();
            var result = new ApiResult();
            result.Code = AjaxCode.Success;
            return result;
        }

    }
}
